<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="500px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="车牌号码" prop="carNo">
              <el-input
                class="data-input"
                v-model="form.carNo"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系人" prop="contact">
              <el-input
                class="data-input"
                v-model="form.contact"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                class="data-input"
                v-model="form.phone"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="单位" prop="unit">
              <el-input
                class="data-input"
                v-model="form.unit"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="访问有效期" prop="time">
              <el-date-picker
                v-model="form.time"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="访问园区" prop="parkIds">
              <el-select
                class="data-input"
                v-model="form.parkIds"
                placeholder="请选择"
                multiple
                clearable
              >
                <el-option
                  v-for="(item, index) of parkOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.pkid"
                  :disabled="item.enable === '0'"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                class="data-input"
                v-model="form.remark"
                placeholder="请输入"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件资料">
              <VUpload v-model="form.files" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否启用">
              <el-radio-group v-model="form.enable">
                <el-radio
                  v-for="(item, index) of dict['yn']"
                  :key="index"
                  :value="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)" :loading="loading"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { cardId } from '@/utils/validate'
import { useDict } from '@/hooks/useDict'
const { dict } = useDict(['yn'])
import VUpload from '@/components/upload/index.vue'
import { CirclePlusFilled, RemoveFilled } from '@element-plus/icons-vue'
import {
  carAdd,
  carUpdate,
  carDetail,
} from '@/api/manager/dataManage/carManage.js'
import { parkPageList } from '@/api/manager/dataManage/park'
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  async () => {
    if (props.detail.pkid && dialogVisible.value) {
      handleDetail()
    }
  },
)
const handleDetail = async () => {
  const res = await carDetail({ pkid: props.detail.pkid })
  if (res.success) {
    // 处理时间
    res.data.time = [res.data.startTime, res.data.endTime]
    // 处理附件资料
    res.data.files = res.data.fileList || []
    delete res.data.fileList
    // 处理访问园区
    res.data.parkIds =
      res.data.parks && res.data.parks.length > 0
        ? res.data.parks.map((i) => {
            return i.pkid
          })
        : []

    form.value = { ...res.data }
  } else {
    ElMessage.error(res.message)
  }
}
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  form.value = {
    type: 2,
    time: [],
    enable: '1',
    files: [],
    parkIds: [],
  }
  formRef.value.clearValidate()
  dialogVisible.value = false
  emit('close', isFlash)
}
watch(
  () => dialogVisible.value,
  async () => {
    if (dialogVisible.value) {
      initParkList()
    }
  },
)
const parkOptions = ref([])
const initParkList = async () => {
  const res = await parkPageList({ pageIndex: 1, pageSize: 9999 })
  parkOptions.value = res.data.list
}
const formRef = ref(null)
const form = ref({
  type: 2,
  time: [],
  enable: '1',
  files: [],
  parkIds: [],
})

const rules = ref({
  carNo: [{ required: true, message: '请输入车牌号码', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[34578]\d{9}$/,
      message: '请输入正确手机号',
      trigger: 'blur',
    },
  ],
  parkIds: [
    {
      required: true,
      message: '请选择访问园区',
      trigger: ['blur', 'change'],
    },
  ],
  time: [{ required: true, message: '请选择访问有效期', trigger: 'blur' }],
})

const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = JSON.parse(JSON.stringify(form.value))
      // 处理时间
      params.startTime = params.time[0]
      params.endTime = params.time[1]
      delete params.time
      // 处理附件资料
      if (params.files && params.files.length > 0) {
        params.files = params.files
          .map((i) => {
            return i.pkid
          })
          .join(',')
      } else {
        params.files = ''
      }
      // 处理访问园区
      params.parkIds =
        params.parkIds && params.parkIds.length > 0
          ? params.parkIds.join(',')
          : ''

      try {
        let res
        if (form.value.pkid) {
          res = await carUpdate(params)
        } else {
          res = await carAdd(params)
        }
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        console.log('error', error)
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
defineExpose({ dialogVisible, title })
onMounted(() => {})
</script>
<style lang="scss" scoped></style>
